import http from '@/utils/request.js'

// ========================================
// 智能问答 API
// ========================================

// 生成答案（支持首次创建会话或继续会话）
export const generateAnswer = ({ 
  question, 
  sessionId = undefined, 
  model = 'deepseek-chat', 
  maxTokens = 1500, 
  temperature = 0.7, 
  deepseekMode, 
  xunfeiVersion, 
  xunfeiMode, 
  knowledgeBaseId 
} = {}) => {
  const payload = {
    question,
    model,
    maxTokens,
    temperature
  }

  if (sessionId) payload.sessionId = sessionId
  if (deepseekMode) payload.deepseekMode = deepseekMode
  if (xunfeiVersion) payload.xunfeiVersion = xunfeiVersion
  if (xunfeiMode) payload.xunfeiMode = xunfeiMode
  if (knowledgeBaseId) payload.knowledgeBaseId = knowledgeBaseId

  return http.post('/qa/generate-answer', payload)
}

// ========================================
// 会话管理 API
// ========================================

// 获取所有会话列表
export const getSessions = () => http.get('/qa/sessions')

// 获取特定会话详情
export const getSessionDetail = (sessionId) => http.get(`/qa/sessions/${sessionId}`)

// 获取会话消息历史
export const getSessionMessages = (sessionId) => http.get(`/qa/sessions/${sessionId}/messages`)

// ========================================
// 向量检索 API
// ========================================

// 语义相似度检索相关文档
export const retrieveChunks = (query, topK = 5) => {
  return http.get('/qa/retrieve-chunks', { query, topK })
}

// 生成文本向量
export const generateEmbedding = (text) => {
  return http.post('/vector/generate-embedding', { text })
}

// ========================================
// 历史记录查询 API
// ========================================

// 获取用户对话记录（支持过滤）
export const getUserConversations = ({
  startDate,
  endDate,
  model,
  page = 1,
  pageSize = 20
} = {}) => {
  const payload = { page, pageSize }
  if (startDate) payload.startDate = startDate
  if (endDate) payload.endDate = endDate
  if (model) payload.model = model
  
  return http.post('/qa/user-conversations', payload)
}

// 获取问答列表（分页）
export const getQAList = (page = 1, pageSize = 10) => {
  return http.get('/qa', { page, pageSize })
}

// ========================================
// 知识库管理 API
// ========================================

// 创建知识库
export const createKnowledgeBase = ({
  knowledgeBaseName,
  knowledgeBaseDescription,
  isPublic = false
}) => {
  return http.post('/knowledgebase', {
    knowledgeBaseName,
    knowledgeBaseDescription,
    isPublic
  })
}

// 获取知识库列表
export const getKnowledgeBaseList = () => http.get('/knowledgebase')

// 获取知识库详情
export const getKnowledgeBaseDetail = (knowledgeBaseId) => {
  return http.get(`/knowledgebase/${knowledgeBaseId}`)
}

// 更新知识库
export const updateKnowledgeBase = (knowledgeBaseId, {
  knowledgeBaseName,
  knowledgeBaseDescription,
  isPublic
}) => {
  return http.put(`/knowledgebase/${knowledgeBaseId}`, {
    knowledgeBaseName,
    knowledgeBaseDescription,
    isPublic
  })
}

// 删除知识库
export const deleteKnowledgeBase = (knowledgeBaseId) => {
  return http.delete(`/knowledgebase/${knowledgeBaseId}`)
}

// ========================================
// 文档管理 API
// ========================================

// 上传文档（自动解析和向量化）
export const uploadDocument = ({
  filePath,
  documentTitle,
  knowledgeBaseId,
  documentAccessLevel = 'private'
}) => {
  const formData = {
    documentTitle,
    knowledgeBaseId,
    documentAccessLevel
  }
  
  return http.upload('/document/upload', filePath, formData)
}

// 批量上传文档
export const batchUploadDocuments = ({
  filePaths,
  knowledgeBaseId,
  documentAccessLevel = 'private'
}) => {
  // 注意：这里需要特殊处理批量上传
  // 由于uni-app的限制，可能需要逐个上传
  const uploadPromises = filePaths.map(filePath => {
    return http.upload('/document/upload', filePath, {
      knowledgeBaseId,
      documentAccessLevel
    })
  })
  
  return Promise.all(uploadPromises)
}

// 查看文档处理状态
export const getDocuments = (knowledgeBaseId) => {
  return http.get('/document', { knowledgeBaseId })
}

// 搜索文档
export const searchDocuments = ({
  keyword,
  knowledgeBaseId,
  page = 1,
  pageSize = 10
}) => {
  return http.post('/document/search', {
    keyword,
    knowledgeBaseId,
    page,
    pageSize
  })
}

// 查看特定文档详情
export const getDocumentDetail = (documentId) => {
  return http.get(`/document/${documentId}`)
}

// 查看文档的文档块列表
export const getDocumentChunks = (documentId) => {
  return http.get(`/document/${documentId}/chunks`)
}

// 重新处理文档（重新分块和向量化）
export const reprocessDocument = (documentId) => {
  return http.post(`/document/${documentId}/reprocess`)
}

// 删除文档
export const deleteDocument = (documentId) => {
  return http.delete(`/document/${documentId}`)
}

// ========================================
// 工具函数
// ========================================

// 格式化日期为ISO字符串
export const formatDateToISO = (date) => {
  if (typeof date === 'string') {
    return new Date(date).toISOString()
  }
  return date.toISOString()
}

// 创建日期范围查询参数
export const createDateRange = (startDate, endDate) => {
  return {
    startDate: formatDateToISO(startDate),
    endDate: formatDateToISO(endDate)
  }
}

// 模型配置预设
export const MODEL_CONFIGS = {
  // DeepSeek 模型系列
  'deepseek-chat': {
    model: 'deepseek-chat',
    deepseekMode: 'chat',
    maxTokens: 1500,
    temperature: 0.7
  },
  'deepseek-reasoner': {
    model: 'deepseek-reasoner',
    deepseekMode: 'reasoner',
    maxTokens: 2000,
    temperature: 0.4
  },
  // 讯飞星火模型系列
  'xunfei-chat': {
    model: 'x1',
    xunfeiVersion: 'v2',
    xunfeiMode: 'chat',
    maxTokens: 1500,
    temperature: 0.7
  },
  'xunfei-reasoner': {
    model: 'x1',
    xunfeiVersion: 'v2',
    xunfeiMode: 'reasoner',
    maxTokens: 2000,
    temperature: 0.5
  }
}

// 获取模型配置
export const getModelConfig = (modelType) => {
  return MODEL_CONFIGS[modelType] || MODEL_CONFIGS['deepseek-chat']
} 